
import React, { useState, FC, useRef } from 'react';
import { Space, Popconfirm, Button, Pagination, ConfigProvider,   } from 'antd';

import { ReloadOutlined, } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';


import {connect, Dispatch, Loading, Router, UserListDataType, useModel} from 'umi';
import {SingleUserInfoType, FormValuesType} from './data';
import CustomModalForUsers from './components/CustomModalForUsers';

import zhCN from 'antd/lib/locale/zh_CN';

import {getUserList} from './service';


interface UserPageProps{
  usersDataArr: SingleUserInfoType[];
  dispatch: Dispatch;
  loadingStatus: boolean;
  meta: any;
};

interface ActionType {
  reload: (resetPageIndex?: boolean) => void;
  reloadAndRest: () => void;
  reset: () => void;
  clearSelected?: () => void;
  startEditable: (rowKey: any) => boolean;
  cancelEditable: (rowKey: any) => boolean;
}


const UserListPage: FC<UserPageProps> = ({ usersDataArr, meta, dispatch, loadingStatus, }) => {

  const columns: any = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <a>{text}</a>,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      // 自动转化为标准时间
      valueType: 'dateTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: SingleUserInfoType) => (
        <Space size="middle">
          <a onClick={ () => handleEditOrEditInfo(record, 'edit') }>编辑</a>
          <Popconfirm
            title="你确定删除吗？"
            onConfirm={confirmDelete}
            okText="确定"
            cancelText="取消"
          >
            <a onClick={ () => handleEditOrEditInfo(record, 'del')} >删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [userInfo, setUserInfo] = useState<SingleUserInfoType | any>({});

  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(6);

  const tableProRef_demo = useRef<any>();

  const result = useModel('yu');
  console.log('使用useModel取出值', typeof result, result.name)


  const handleEditOrEditInfo = (record: SingleUserInfoType, keyWord: string) => {
    if(keyWord === 'edit'){
      setIsModalVisible(true);
      setUserInfo(record);
    } else {
      setUserInfo(record);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setUserInfo({});
  };


  const handleFinish = (values: FormValuesType) => {
    console.log('Success: 收集到子组件的表单数据', values);
    const id = userInfo.id;
    if(id){
      dispatch({
        type: 'tablePro/editUpdateInfo',
        payload: {
          values,
          id
        }
      });
    } else {
      dispatch({
        type: 'tablePro/addUserInfo',
        payload: {
          values
        }
      })
    }

    setIsModalVisible(false);
  };


  const confirmDelete = () => {
    if(userInfo.id){
      dispatch({
        type: 'tablePro/deleteUserInfo',
        payload: {
          id: userInfo.id ,
        }
      })
    }

  };



  // 若不使用model的subscriptions, 则表格中的request请求是初始默认执行一次
  const handleRequestTableData = async (params: any, sorter: any, filter: any) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    console.log('params参数分类-----table参数', params);

    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
    // 如果需要转化参数可以在这里进行修改
    const data = {
      page: params.current || current,
      per_page: params.pageSize || pageSize,
    };

    const res = await getUserList(data);
    console.log('后端返回---res结果', res);

    if(res){
      // 封装成和model中的meta结构一样
      const meta = {
        total: res.meta.total,
        per_page: res.meta.per_page,
        page: res.meta.page,
      };

      // 仅仅修改meta的状态
      /*dispatch({
        type: 'tablePro/updateDemoData',
        payload: {
          meta
        }
      });*/

      // 封装成所需要的数据格式
      const needData = {
        userArr: res.data,
        meta: res.meta
      };

      dispatch({
        type: 'tablePro/updateDemoData',
        payload: needData
      });

      return {
        data: res.data,
        // success 请返回 true, 不然 table 会停止解析数据，即使有数据
        success: true,
        // 不传会使用 data 的长度，如果是分页一定要传
        total: res.meta.total,
      };
    } else {
      return {
        data: [],
      }
    }



  };


  const handleAddUser = () => {
    setUserInfo({});
    setIsModalVisible(true);
  };

  const toRefresh = () => {
    // 使用ref 调用和使用proTable的刷新功能
    tableProRef_demo.current.reload();
  };

  const changePagination = (page: number, pageSize?: number) => {
    console.log('改变', page, pageSize );

    setCurrent(page);
    setPageSize(pageSize || meta.per_page );

    const params = {
      current: page,
      pageSize
    };

    handleRequestTableData(params, {}, {});

  };


  return (
    <div className='list-table'>

      <ProTable
        actionRef={tableProRef_demo}
        columns={columns}
        dataSource={usersDataArr}
        loading={loadingStatus}
        request={handleRequestTableData}
        rowKey={record => record.id}
        pagination={false}
        search={false}
        headerTitle={ result.name + '学习react 17、TS、tablePro的基本使用' }
        toolBarRender={() => [
          <Button type='primary' onClick={handleAddUser}> 添加用户</Button>,
          <Button type="primary" ghost key="primary" onClick={toRefresh}>刷新<ReloadOutlined /></Button>,
        ]}
      />

      <ConfigProvider locale={zhCN}>
        <Pagination
          className='pagination_style'
          total={meta.total}
          showSizeChanger
          showQuickJumper
          showTotal={total => `共计 ${total} 人`}
          onChange={changePagination}
          current={current}
          pageSize={pageSize}
        />
      </ConfigProvider>





      <CustomModalForUsers
        isVisible={isModalVisible}
        clickCancel={handleCancel}
        handleFinish={handleFinish}
        info={userInfo}
        confirmLoading={loadingStatus}
      />

    </div>
  )
};



// 注： 这里是namespace
const mapStateToProps = ({tablePro, loading, router}: {tablePro: UserListDataType, loading: Loading, router: Router}) => {
  // console.log('参数', val);
  // console.log('namespace命名', tablePro, loading, router);
  return {
    usersDataArr: tablePro.userArr,
    meta: tablePro.meta,
    loadingStatus: loading.models.tablePro,
    router,
  }
};


export default connect(mapStateToProps)(UserListPage);



/*
// 简写形式
export default connect(({tablePro, loading, router})=> ({
  users: tablePro.data,
  loading,
  router,
}))(UserListPage);

*/
